package com.leetcode;

/**
 * 211. 添加与搜索单词 - 数据结构设计
 * 使用 固定 26 数组
 *
 * @author fy
 * @date 2022/4/19 11:46
 */
public class Solution211_1 {

    class WordDictionary {

        private WordDictionary[] children;
        private boolean isEnd;

        public WordDictionary() {
            this.children = new WordDictionary[26];
            this.isEnd = false;
        }

        public void addWord(String word) {
            WordDictionary node = this;
            for (int i = 0; i < word.length(); i++) {
                int index = word.charAt(i) - 'a';
                if (node.children[index] == null) {
                    node.children[index] = new WordDictionary();
                }
                node = node.children[index];
            }
            node.isEnd = true;
        }

        public boolean search(String word) {
            return dfsSearch(word, 0, this);
        }

        private boolean dfsSearch(String word, int index, WordDictionary node) {
            if (index == word.length()) {
                return node.isEnd;
            }
            char ch = word.charAt(index);
            int idx = ch - 'a';
            if (ch != '.') {
                if (node.children[idx] == null) {
                    return false;
                }
                return dfsSearch(word, index + 1, node.children[idx]);
            } else {
                for (WordDictionary child : node.children) {
                    if (child != null && dfsSearch(word, index + 1, child)) {
                        return true;
                    }
                }
                return false;
            }
        }

    }

}
